<template>
  <div class="practice">
    <van-nav-bar :title="mode.title" left-text="返回" left-arrow @click-left="router.back()" />
    <div class="practice-content" v-if="currentQuestion">
      <van-cell-group inset>
        <van-cell :title="currentQuestion.title" :label="currentQuestion.description" />
      </van-cell-group>
      <van-cell-group inset class="speech-input">
        <van-field v-model="resultText" rows="3" type="textarea" :border="false" autosize required
          placeholder="语音识别内容将显示在这里，您也可以手动编辑" />
      </van-cell-group>

      <div class="submit-container">
        <van-button type="primary" size="large" :loading="isRecording" @mousedown.prevent="startRecognition"
          @mouseup.prevent="stopRecognition" @touchstart.prevent="startRecognition" @touchend.prevent="stopRecognition">
          {{ isRecording ? '正在录音...' : '按住说话' }}
        </van-button>

        <van-button type="success" size="large" :loading="isSubmitting" :disabled="isRecording || !resultText"
          @click="handleSubmit">
          提交答案
        </van-button>
      </div>

      <van-cell-group inset v-if="feedback" class="feedback">
        <van-cell title="AI 评分" :value="feedback.score + '分'" />
        <!-- <van-cell title="发音评价" :label="feedback.pronunciation" /> -->
        <van-cell title="语法建议" :label="feedback.grammar" />
        <van-cell title="表达建议" :label="feedback.expression" />
      </van-cell-group>
    </div>
    <van-empty v-else description="暂无练习题目" />
  </div>
  <div class="notice" v-if="feedback">
    <van-button type="danger" round @click="fetchQuestions">
      <van-swipe vertical class="notice-swipe" :autoplay="2000" :touchable="false" :show-indicators="false">
        <van-swipe-item v-if="feedback && feedback.score > 6">请继续💪</van-swipe-item>
        <van-swipe-item v-else>很棒👍</van-swipe-item>
        <van-swipe-item>再做一次</van-swipe-item>
      </van-swipe>
    </van-button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'

const route = useRoute()
const router = useRouter()
// 初始化语音识别
let recognition = null
const isRecording = ref(false)
const isSubmitting = ref(false)
let resultText = ref('')
try {
  recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)()
  recognition.continuous = true
  recognition.interimResults = true
  recognition.onresult = (event) => {
    let result = event.results[0]
    // 更新显示文本，优先使用最终结果，如果没有则使用临时结果
    resultText.value = event.results[0][0].transcript;
    
    console.log('语音识别结果更新:', resultText.value);
  }
  // 添加错误处理
  recognition.onerror = (event) => {
    console.error('语音识别错误:', event.error, event)
  }
  
  // 添加开始和结束事件处理
  recognition.onstart = () => {
    console.log('语音识别已开始')
  }
  
  recognition.onend = () => {
    console.log('语音识别已结束')
    console.log('当前识别文本:', resultText.value)
  }
} catch (error) {
  console.error('语音识别对象初始化失败:', error)
}
const mode = computed(() => {
  const modes = {
    ielts: { title: '雅思口语模拟', type: 'exam' },
    daily: { title: '日常对话练习', type: 'conversation' },
    business: { title: '职场英语训练', type: 'business' }
  }
  return modes[route.query.mode] || modes.daily
})
// 模拟题目数据
const currentQuestion = ref({
  title: '描述你最喜欢的一本书',
  description: '请谈谈这本书的内容，以及为什么它对你产生了深刻的影响。'
})
  
const feedback = ref(null)

// 开始录音
const startRecognition = () => {
  try {
    isRecording.value = true
    recognition.start()
  } catch (error) {
    console.error('开始录音时发生错误:', error)
  }
}

// 停止录音并发送到AI
const stopRecognition = () => {
  try {
    isRecording.value = false
    recognition.stop()
  } catch (error) {
    console.error('停止录音时发生错误:', error)
  }
}

// 提交答案到后端
const handleSubmit = async () => {
  if (!resultText.value.trim()) {
    showToast('请先录入或输入内容')
    return
  }
  
  try {
    isSubmitting.value = true
    // 构建提交数据
    const submitData = {
      text: resultText.value,
      mode: mode.value.type,
      title: currentQuestion.value.title,
      description: currentQuestion.value.description,
      questionId: currentQuestion.value?.questionId || '1',
    }
    // 模拟API调用
    // 实际项目中应该替换为真实的API调用，例如：
    const response = await fetch('/api/v1/practice/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(submitData)
    })
    const {data} = await response.json()
    data.score = parseInt(data.score)
    // 更新反馈数据
    feedback.value =  data
    showToast({
      type: 'success',
      message: '提交成功',
      position: 'bottom'
    })
    
  } catch (error) {
    console.error('提交答案时发生错误:', error)
    showToast({
      type: 'fail',
      message: '提交失败，请重试',
      position: 'bottom'
    })
  } finally {
    isSubmitting.value = false
  }
}
// 从服务端API获取练习题目
const fetchQuestions = async () => {
  showToast({
    type: 'loading',
    message: '正在获取练习题目',
  })
  resultText.value = ''
  feedback.value = null
  try {
    const response = await fetch(`/api/v1/questions?mode=${route.query.mode || 'daily'}`)
    const data = await response.json()
    if (data.success && data.data != undefined) {
      currentQuestion.value = data.data
      console.log('练习题目加载完成', currentQuestion.value)
    } else {
      console.warn('未获取到练习题目数据')
      showToast({
        type: 'warning',
        message: '未获取到练习题目',
        position: 'middle'
      })
    }
  } catch (error) {
    console.error('获取练习题目失败:', error)
    showToast({
      type: 'fail',
      message: '获取题目失败，请重试',
      position: 'bottom'
    })
  }
}
onMounted(() => {
  // 立即执行函数 - 用于初始化数据和配置
  // 这里可以放置一些初始化逻辑
  // 例如：预加载练习题目、设置语音识别的初始配置等
  // 执行初始化操作
  fetchQuestions()
})

</script>

<style scoped>
.practice {
  max-width: 768px;
  /* max-height: 1024px; */
  width: 100%;
  margin: 0 auto;
  overflow-y: auto;
  background-color: var(--primary-bg);
  color: var(--text-primary);
}

.practice-content {
  padding: 20px;
  background-color: var(--primary-bg);
  color: var(--text-primary);
}

.controls {
  margin: 30px 16px;
  display: flex;
  justify-content: space-around;
}

.controls .van-button {
  width: 100%;
  height: 48px;
  font-weight: 500;
  border-radius: var(--radius-sm);
  background-color: var(--accent-color);
  border: none;
  transition: all 0.3s ease;
}

.controls .van-button:active {
  background-color: var(--accent-color-dark);
  transform: scale(0.98);
}

.feedback, .speech-input {
  margin: 20px 16px;
  padding: 0px;
  background-color: var(--card-bg);
  border-radius: var(--radius-md);
  /* border: 1px solid var(--border-color); */
  box-shadow: var(--shadow-md);
  overflow: hidden;
}

.speech-input {
  margin-top: 20px;
}

.submit-container {
  margin: 20px 16px 30px;
  display: flex;
  justify-content: space-around;
}

.submit-container .van-button {
  width: 40%;
  height: 44px;
  font-weight: 500;
  border-radius: var(--radius-sm);
  background-color: var(--success-color, #07c160);
  border: none;
  transition: all 0.3s ease;
}

.submit-container .van-button:active {
  opacity: 0.9;
  transform: scale(0.98);
}

.notice {
  position: absolute;
  right: 10px;
  bottom: 50px;
}
.notice .notice-swipe {
    height: 40px;
    line-height: 40px;
    font-size: 12px;
  }
</style>